package com.dolceplan.dolceapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class DolceAppService extends Service {

    public static final String BROADCAST_ACTION = "UpdateOffers";

	private final Handler handler = new Handler();
	    Intent intent;
	    int counter = 0;
	
	public DolceAppService() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	
	}
	
	public void onCreate() {
        super.onCreate();
    	intent = new Intent(BROADCAST_ACTION);	
	}
	
	@Override
    public void onStart(Intent intent, int startId) {
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); 
        
        
        
        LocationListener mlocListener = new LocationListener() {
									
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				//tvResults.setText(provider + " enabled");
			}
				
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				//tvResults.setText(provider + " disabled");
			}
				
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				//tvResults.setText("Latitude: " + location.getLatitude() + "; Longitude: " + location.getLongitude());
				DolceApp dolceApp = (DolceApp) getApplication();
				//dolceApp.setLocation(location);
				check(location);
			}
	
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
		};

		LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 20, mlocListener); // el listener que configura el GPS
     
    }
	
	
	
	private Runnable sendUpdatesToUI = new Runnable() {
    	public void run() {
    	    DisplayLoggingInfo();    		
    	    handler.postDelayed(this, 5000); // 5 seconds
    	}
    	
    private void DisplayLoggingInfo() {
        	Log.d("service", "entered DisplayLoggingInfo");
           	intent.putExtra("time", new Date().toLocaleString());
        	intent.putExtra("counter", String.valueOf(++counter));
        	sendBroadcast(intent);
        }
    };

    
private void check(Location location) {
    	
    	String ip = "http://www.osvid.org/DolceServer/getOffer_2.php";
    	//String lat = Double.toString(location.getLatitude());
    	//String lon = Double.toString(location.getLongitude());
    	
	    Location loc = new Location(location);
	    
    	String resultSQL = "";
       	String result = "";
       	
    	
        InputStream is = null;
		
        /*the data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("lat", lat));
        nameValuePairs.add(new BasicNameValuePair("lon", lon));          
        */
        
        
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(ip);
                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }   	
    	
        
        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                resultSQL=sb.toString();
                Log.i("info", resultSQL);
                        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
        
        try{
        	ArrayList<Offer> offerList;
        	Gson gson = new Gson();        	      	           	
        	Type listType = new TypeToken<ArrayList<Offer>>() {}.getType();
        	offerList = gson.fromJson(resultSQL, listType );        	
        	Log.i("gson", "# de ofertas:" + String.valueOf(offerList.size()));        	
        	        	
            //Get our Application Instance
        	//DolceApp dolceApp = (DolceApp) getApplication();
        	//Set the app string on our app instance
        	DolceApp dolceApp = (DolceApp) getApplication();
        	dolceApp.setOfferList(offerList);        	        	
        	result = dolceApp.getOffer(1).getLatitude().toString();
        	
        } finally {
        	
        }
}
}
	    


